// 开发配置
import { uniSetStorageSync, uniSetToken, uniSetUser } from './funcs';
import { USER_ORIENTED } from './config';
import { imService } from '@/util/rongCloud/cloudUtil';

// 系统配置
export const QQ_MAP_KEY = 'HQKBZ-MUH63-IIM3U-YNVUP-NCIFQ-3UFUQ';

//  常量
export const ANIMATION_TIME = 200;
export const T_FADE_SLIDE_TOP = ['fade', 'slide-top'];
export const TOAST_DURATION = 1500;
export const SHORT_TOAST_DURATION = 1000;
export const EX_SHORT_TOAST_DURATION = 500;
export const CHAT_HOUSE_CARD = '#4GF_JU#HOUSE_CARD#';

// uni 存储key
export const TOKEN_key = 'token';
export const CURRENT_USER_KEY = 'currentUser'; // 详细结构查看userData.js
export const MY_LOCATION = 'MY_LOCATION';
// 精确定位, 包含经纬度  ad_info.location = {"lat": 22.53212,"lng": 114.125}
export const FINE_LOCATION = 'FINE_LOCATION';

export const CHAT_MEMBERS = 'member'; // 所有聊天对象

/**
 * 当前招商人员最近一次发送的卡片house id是什么
 * @param rongcloud_id  聊天对象的聊天id
 * @returns {string} 用于标志缓存
 */
export function lastTimeHouse(rongcloud_id) {
  return 'talkHouseCard' + rongcloud_id;
}

// 必须要和 hx 聊天id一起存放
export const PROFILE_OF = 'profileOf';
export const hx_LIST_GROUP = 'listGroup';

/* structure 如下
address: {
    province: '',
    city: '',
    district: '',
  },
*/

// 聊天双方的用户名, 这里的用户名统一都是easemob_account_password,
/* 结构如下:
{
  myName: (...)
  your: (...)
}
 * */
export const CHATTERS_NAMES = 'chattersName';

export const ROUTER_OBJ = 'ROUTER_OBJ';
export const SECOND_ROUTER_OBJ = 'routerObj2';
export const SEARCH_HISTORY_ARR = 'searchHistoryArray'; // search.vue

// 其他
export const PROVIDER_WECHAT = 'weixin';

// 仿制当前用户数据
export const mockPersonData = {
  id: 1,
  username: 'lysander',
  name: '诸葛春雨',
  department: '华嵘大厦分店',
  workAddress:
    '启租网-华嵘大厦分店启租网-华嵘大厦分店启租网-华嵘大厦分店启租网-华嵘大厦分店启租网-华嵘大厦分店启租网-华嵘大厦分店',
  phone: '13877888888',
  // 图片
  profilePhoto:
    'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1602678654472&di=0dd11647f3cda0968678d7204b0b2513&imgtype=0&src=http%3A%2F%2Fp3.ssl.cdn.btime.com%2Ft01de3f55f1ebf79c5f.jpg%3Fsize%3D440x440',
};

// 取得路由参数
export function getRouterParam() {
  return uni.getStorageSync(ROUTER_OBJ);
}

// 会把原来的信息 保留, 只添加或更新旧的值
export function updateUniStorage(key, newObj) {
  let past = uni.getStorageSync(key);
  uni.setStorageSync(key, {
    ...past,
    ...newObj,
  });
}

export function ifNoTokenThenLogin(toCheck) {
  if (!toCheck) {
    d_uniShowToast({
      title: '请登录',
      success: (res) => {
        uniNavigate('/login/loginPassword');
      },
    });
  }
}

/**
 * 清空用户数据
 *
 * 功能:
 *  - 清除用户信息,
 *  - 断开融云连接
 * @param vm vue实例
 */
export function clearUserInfo(vm) {
  if (USER_ORIENTED) {
    // 清空当前用户
    uniSetStorageSync(CURRENT_USER_KEY, undefined);
    // 清空token
    uniSetStorageSync(TOKEN_key, '');
  } else {
    uniSetUser(vm, undefined);
    uniSetToken(vm, '');
    uniSetStorageSync('uuid', undefined);
    console.log('clear current user cache over');
  }

  imService.disconnect().then(() => {
    // console.log('断开链接成功'))
  });
}

// 表单校验
// 密码强度校验 link:https://juejin.im/post/6844903573348696072
// 规则: 含大小写和数字,最短8位,最长25位,
export const PASSWORD_PATTERN = '^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[^]{8,25}$';

export const phone_verify_rule = [
  {
    name: 'phone',
    checkType: 'phoneno',
    errorMsg: '手机号码输入错误',
  },
];

export const phone_pwd_verifyCode_RULE = [
  {
    name: 'phone',
    checkType: 'phoneno',
    errorMsg: '手机号码输入错误',
  },
  {
    name: 'code',
    checkType: 'string',
    checkRule: '4,4',
    errorMsg: '验证码输入错误',
  },
  {
    name: 'password',
    checkType: 'reg',
    checkRule: PASSWORD_PATTERN,
    errorMsg: '密码校验失败, 包含大小写和数字,最短8位,最长25位',
  },
];

export const Apple_Phone_pwd_verifyCode_RULE = [
  {
    name: 'phone',
    checkType: 'phoneno',
    errorMsg: '手机号码输入错误',
  },
  {
    name: 'code',
    checkType: 'string',
    checkRule: '4,4',
    errorMsg: '验证码输入错误',
  }
];

let graceChecker = require('./graceChecker.js');

/**
 * @description:  表单校验方法
 * return: checkRes: true 成功, false 失败
 */
export function passFormCheck(obj, ruleArr, checkPassword, icon) {
  let customErr = '';
  let checkRes = graceChecker.check(obj, ruleArr);

  if (checkPassword && obj.password) {
    if (obj.password !== obj.passwordAgain) {
      checkRes = false;
      customErr = '两次密码输入不一致';
    }
  }

  if (!checkRes) {
    console.log(graceChecker);
    uni.showToast({
      title: graceChecker.error || customErr,
      icon: icon || 'none',
      duration: 3000,
    });
  }
  return checkRes;
}

// 表单校验 END

// commonToastObj: 不显示图标, 2s看动画
export function commonToastOpt_noIcon() {
  return {
    duration: TOAST_DURATION,
    icon: 'none',
    position: 'bottom',
  };
}

// deprecate: 还是用下面这个显示toast 比较方便, 在webStorm 可以快速打出这个函数
export function d_uniShowToast(opt, toMask = true) {
  uni.showToast({
    ...commonToastOpt_noIcon(),
    ...opt,
    mask: toMask,
  });
}

export function tips(msg) {
  uni.showToast({
    ...commonToastOpt_noIcon(),
    title:msg
  });
}

export function uniShowToast(title, toMask = true, opt) {
  return new Promise((resolve) => {
    uni.showToast({
      title: title,
      duration: TOAST_DURATION,
      icon: 'none',
      position: 'bottom',
      ...opt,
      mask: toMask,
      complete: (res) => {
        // console.log('uniShowToast res: ',res);
        resolve(res);
      },
    });
  });
}

export function uniBack() {
  uni.navigateBack();
}

export function uniNavigate(url, opt, cb) {
  uni.navigateTo({
    url: '/pages' + url,
    // 本项目不采取路径后面带参数的方法, 貌似一个个拼接挺麻烦的 , 统一使用uni storage ROUTER_OBJ
    /** (先看上一句话)  路径后可以带参数。参数与路径之间使用?分隔，参数键与参数值用=相连，不同参数用&分隔；
     如 'path?key=value&key2=value2'，path为下一个页面的路径，
     下一个页面的onLoad函数可得到传递的参数 **/

    success: (res) => {
      // console.log(res)
      cb && cb();
    },
    fail: (res) => {
      console.error(res);
    },
    ...opt,
  });
}

// 工具函数, 页面内有用
// 判断需不需要再地名后面加个市
export function toAppendShi(str) {
  if (!str) return '';
  if (str.endsWith('市') || str.endsWith('县') || str.endsWith('州')) {
    return str;
  } else {
    return str + '市';
  }
}

function confirmEnding(str, target) {
  return str.endsWith(target);
}

//  计算房源租售类型：1租  2售 3租售 4已租 5已售 6资料房 7暂停房 8司租 9司售
export function getHouseTag(val) {
  let res;
  switch (val) {
    case 1:
      res = '租';
      break;
    case 2:
      res = '售';
      break;
    case 3:
      res = '租售';
      break;
    case 4:
      res = '已租';
      break;
    case 5:
      res = '已售';
      break;
    case 6:
      // res = '资料盘';
      res = '资料房';
      break;
    case 7:
      // res = '暂停盘';
      res = '暂停房';
      break;
    case 8:
      res = '司租';
      break;
    case 9:
      res = '司售';
      break;
    default: {
      res = 'error';
      // console.log(res,val);
    }
  }
  return res;
}

// 发送信息不可为空
export function isBlank(str) {
  str.replace(/(^\s*)|(\s*$)/g, '');
  return str === '';
}

/**
 * 参照写法
 String.prototype.trim = function () {
  return this.replace(/(^\s*)|(\s*$)/g, "");
};
 if (!this.userMessage.trim()) {
  return;
}
 */

export function get_uuid() {
  var s = [];
  var hexDigits = '0123456789abcdef';
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = '4'; // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = '-';

  var uuid = s.join('');
  return uuid;
}
